package com.bawei.mall.product.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.DateUtils;
import com.bawei.common.core.utils.addrs.AnalyzeAddress;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.common.rabbit.domain.Message;
import com.bawei.common.rabbit.enums.QueueEnum;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.*;
import com.bawei.mall.product.domain.detail.ProductAttribute;
import com.bawei.mall.product.domain.detail.ProductAttributeValue;
import com.bawei.mall.product.domain.detail.SkuStock;
import com.bawei.mall.product.domain.model.ProductModel;
import com.bawei.mall.product.domain.model.SkuModel;
import com.bawei.mall.product.domain.reponse.ProductDetailsNewResponse;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.domain.request.ProductInfoRequest;
import com.bawei.mall.product.service.*;
import com.bawei.system.domain.IndexCreateRequest;
import com.bawei.system.domain.model.User;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.remote.api.RemoteEsDocService;
import com.bawei.system.remote.api.RemoteEsIndexService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.bawei.mall.product.mapper.MallProductInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 商品信息Service业务层处理
 *
 * @author DongZeLiang
 * @date 2022-09-19
 */
@Service
@Slf4j
public class MallProductInfoServiceImpl implements IMallProductInfoService {
    @Autowired
    private MallProductInfoMapper mallProductInfoMapper;

    @Autowired
    private IMallProductSkuInfoService skuInfoService;

    @Autowired
    private IMallProductRuleInfoService ruleInfoService;


    @Autowired
    private ProductInfoCache productInfoCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RemoteEsDocService remoteEsDocService;

    @Autowired
    private RemoteEsIndexService remoteEsIndexService;

    @Autowired
    private IMallProductTypeInfoService productTypeInfoService;

    @Autowired
    private IMallProductBrandInfoService productBrandInfoService;

    @Autowired
    private IMallProductRuleInfoService productRuleInfoService;

    @Autowired
    private MallProductBrandInfoServiceImpl productBrandInfoServiceImpl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AnalyzeAddress analyzeAddress;

    /**
     * 项目启动时，把商品数据初始化到ES中
     */
//    @PostConstruct
    public void init() {
        loadingProductInfoToEs();
    }

    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ProductInfoResponse selectMallProductInfoById(Long id) {
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        ProductInfoResponse productInfoResponse = new ProductInfoResponse();
        BeanUtils.copyBeanProp(productInfoResponse, mallProductInfo);
        productInfoResponse.setSkuInfoList(
                skuInfoService.selectMallProductSkuInfoList(new MallProductSkuInfo() {{
                    setProductId(id);
                }})
        );
        return productInfoResponse;
    }

    @Override
    public ProductDetailsResponse selectProductDetailsById(Long productId) {
        if (productId == null || productId == 0) {
            throw new ServiceException("查询商品信息，依据不合法！");
        }
        ProductDetailsResponse productDetailsResponse = new ProductDetailsResponse();
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(productId);
        if (productModel == null) {
            throw new ServiceException("查询商品信息，商品数据为空");
        }
        productDetailsResponse.setProduct(productModel);
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);
        if (mallProductSkuInfos == null || mallProductSkuInfos.size() == 0) {
            throw new ServiceException("查询商品信息，SKU数据为空");
        }
        productDetailsResponse.setSkuList(mallProductSkuInfos);
        MallProductRuleInfo ruleInfo = ruleInfoService.selectMallProductRuleInfoById(productModel.getRuleId());
        if (ruleInfo == null) {
            throw new ServiceException("查询商品信息，规格数据为空");
        }
        productDetailsResponse.setProductRule(ruleInfo);
        return productDetailsResponse;
    }

    /**
     * 查询商品信息列表
     *
     * @param mallProductInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<MallProductInfo> selectMallProductInfoList(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoList(mallProductInfo);
    }

    /**
     * 新增商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setCreateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest);
        if (i == 0) {
            return i;
        }

        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );

        // 给搜索系统发送消息需要进行搜索更新
        try {
            rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                    Message.builderMsg(productInfoRequest.getId()));
        } catch (ServiceException serviceException) {
            throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
        }
        return i;
    }

    /**
     * 修改商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.updateMallProductInfo(productInfoRequest);
        if (i == 0) {
            //将商品信息推送至MQ，异步更新ES
            try {
                rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                        Message.builderMsg(productInfoRequest.getId()));
            } catch (ServiceException serviceException) {
                throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
            }
            return i;
        }
        skuInfoService.deleteMallProductSkuInfoByProductId(productInfoRequest.getId());
        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );
        return i;
    }

    /**
     * 批量删除商品信息
     *
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoByIds(Long[] ids) {
        skuInfoService.deleteMallProductSkuInfoByProductIds(ids);
        for (Long id : ids) {
            // 延迟执行
            productInfoCache.delayRemove(id);
        }
        return mallProductInfoMapper.deleteMallProductInfoByIds(ids);
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoById(Long id) {
        return mallProductInfoMapper.deleteMallProductInfoById(id);
    }

    /**
     * 商品总条数
     *
     * @param mallProductInfo 商品查询
     * @return
     */
    @Override
    public Long selectMallProductInfoCount(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
    }


    public static final String INDEX_NAME = "mall_product";


    /**
     * 商品上下架
     *
     * @param id
     * @param isUpload
     * @return
     */
    @Override
    @Transactional
    public void uploadInfo(Long id, boolean isUpload) {
        // 参数校验
        if (null == id){
            throw new ServiceException("商品ID不能为空");
        }
        //查询商品信息
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        if (mallProductInfo == null) {
            throw new ServiceException("商品ID：" + id + "不存在");
        }
        //查询商品skuInfo
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(id);
        if (CollectionUtils.isEmpty(mallProductSkuInfos)){
            throw new ServiceException("商品ID：" + id + "sku信息不存在");
        }

        // 上架
        int updstatus = isUpload ? 1 : 0;
        if (updstatus == 1){
            mallProductInfoMapper.uploadInfo(id,updstatus);
            log.info("上架成功");
            //调用ES查询索引是否存在
            R<Boolean> indexExit = remoteEsIndexService.indexExit(INDEX_NAME);
            if (!indexExit.getData()) {
                log.info("mall_product索引不存在,调用ES服务创建索引");

                //TODO 创建索引，需要指定mappings,mappings从resource下的json文件获取
                Map<String,Object> mappings = getMappingsByResource();
                IndexCreateRequest request = new IndexCreateRequest();
                request.setIndexName(INDEX_NAME);
                if (mappings!=null){
                    request.setMappings(mappings);
                    R<Boolean> indexCreate = remoteEsIndexService.indexCreate(request);
                    if (!indexCreate.isSuccess()) {
                        log.info("索引已存在");
                    }
                }
            }

            //批量同步商品信息到ES
            //参数转换
            List<EsDocInsertVo> esDocInsertVos = tansFromData1(mallProductInfo, mallProductSkuInfos);
            System.out.println(esDocInsertVos);
            //调用ES服务批量插入文档
            R<Boolean> booleanR = remoteEsDocService.batchInsertDocs(esDocInsertVos);
            if (!booleanR.isSuccess()) {
                int errstatus = 2;
                mallProductInfoMapper.uploadInfo(id,errstatus);
                log.info("批量同步商品信息到ES失败");
            }
        }
        // 下架
        if (updstatus == 0){
            //获取sku的ID
            List<String> ids = mallProductSkuInfos.stream().map(item -> {
                return String.valueOf(item.getId());
            }).collect(Collectors.toList());
            //调用ES服务删除文档
            R<Boolean> booleanR = remoteEsDocService.deleteDocs(INDEX_NAME,ids);
            if (booleanR.isSuccess()) {
                mallProductInfoMapper.uploadInfo(id,updstatus);
                log.info("下架成功");
            }
        }
    }


    private List<EsDocInsertVo> transFormData(MallProductInfo mallProductInfo, List<MallProductSkuInfo> productSkuInfoList) {
        //构建返回结果集
        ArrayList<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        //
        productSkuInfoList.forEach(mallProductSkuInfo -> {
            //sku   ES实体类
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(mallProductSkuInfo.getId().toString());
            esDocInsertVo.setIndexName(INDEX_NAME);
            Map<String,Object> data = JSON.parseObject(JSON.toJSONString(mallProductSkuInfo), Map.class);
            data.put("skuId",mallProductSkuInfo.getId());
            //补全spu信息
            data.put("spuId",mallProductInfo.getId());
            data.put("spuName",mallProductInfo.getName());
            data.put("spuDesc",mallProductInfo.getProductDesc());
            data.put("spuCreateTime",mallProductInfo.getCreateTime());
            //字典值转换 补全
            if (mallProductInfo.getType()!= null){
                data.put("type",mallProductInfo.getType());
                data.put("typeName",productTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getType())).getName());
            }
            if(mallProductInfo.getBrand()!=null){
                data.put("brand",mallProductInfo.getBrand());
                data.put("brandName",productTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getBrand())).getName());
            }
            //TODO ES保存集合(图片集)，并能使用kibana查出来
            List<String> arrayList = new ArrayList<>();
            if (mallProductInfo.getImg()!=null){
                arrayList.add(mallProductInfo.getImg());
            }
            if (mallProductInfo.getCarouselImages()!=null){
                String[] split = mallProductInfo.getCarouselImages().split(",");
                arrayList.addAll(Arrays.asList(split));
            }
            mallProductSkuInfo.setImages(arrayList);
            //
            data.put("allImages",mallProductSkuInfo.getImages());

            //data赋值
            esDocInsertVo.setData(data);
            //添加sku对象
            esDocInsertVos.add(esDocInsertVo);
        });

        return esDocInsertVos;
    }







    private List<EsDocInsertVo> tansFromData1(MallProductInfo mallProductInfo, List<MallProductSkuInfo> mallProductSkuInfos) {
        //构建返回结果集
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        mallProductSkuInfos.stream().forEach(mallProductSkuInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(String.valueOf(mallProductSkuInfo.getId()));
            esDocInsertVo.setIndexName(INDEX_NAME);
            esDocInsertVo.setTypeName("_doc");
            // TODO sku信息
//            mallProductSkuInfo.setMallProductInfo(mallProductInfo);
//            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(mallProductSkuInfo), Map.class);
            HashMap<String, Object> map = new HashMap<>(Map.class.getModifiers());
            ArrayList<String> suggestFiled = new ArrayList<>();
            if (mallProductInfo.getImg() != null && mallProductInfo.getCarouselImages() != null){
                ArrayList<String> image = new ArrayList<>();
                image.add(mallProductInfo.getImg());
                image.add(mallProductInfo.getCarouselImages());
//                strings.addAll(List.of(mallProductInfo.getCarouselImages().split(",")));
                map.put("productImages",image);
            }
            if (mallProductInfo.getRuleId() != null){
                map.put("productRuleId",mallProductInfo.getRuleId());
//                map.put("productRuleName",productRuleInfoService.selectMallProductRuleInfoById(mallProductInfo.getRuleId()).getName());
                String productRuleName = productRuleInfoService.selectMallProductRuleInfoById(mallProductInfo.getRuleId()).getName();
                map.put("productRuleName",productRuleName);
                suggestFiled.add(productRuleName);
            }
            if (mallProductInfo.getType() != null){
                map.put("productTypeId",mallProductInfo.getType());
//                map.put("productTypeName",productTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getType())).getName());
                String productTypeName = productTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getType())).getName();
                map.put("productTypeName",productTypeName);
                suggestFiled.add(productTypeName);
            }
            if (mallProductInfo.getBrand() != null){
                map.put("productBrandId",mallProductInfo.getBrand());
//                map.put("productBrandName",productBrandInfoService.selectMallProductBrandInfoById(Long.valueOf(mallProductInfo.getBrand())).getName());
                String productBrandName = productBrandInfoService.selectMallProductBrandInfoById(Long.valueOf(mallProductInfo.getBrand())).getName();
                map.put("productBrandName",productBrandName);
                suggestFiled.add(productBrandName);
            }
//            map.put("productDesc",mallProductInfo.getProductDesc());
            String productDesc = mallProductInfo.getProductDesc();
            map.put("productDesc",productDesc);
            suggestFiled.add(productDesc);
            map.put("spuId",mallProductInfo.getId());
            map.put("skuId",mallProductSkuInfo.getId());
            map.put("suggestFiled",suggestFiled);

            // data赋值
            esDocInsertVo.setData(map);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }


    /**
     * 获取product_info.json 中的map集合
     * @return
     */
    private Map<String, Object> getMappingsByResource() {

        // 定义JSON文件的路径
        String jsonFilePath = "/esmappings/product_info.json"; // 确保文件路径正确

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try (InputStream inputStream = getClass().getResourceAsStream(jsonFilePath)) {
            if (inputStream == null) {
                throw new IllegalArgumentException("File not found: " + jsonFilePath);
            }
            // 读取JSON文件并解析为Map
            return objectMapper.readValue(inputStream, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常或抛出自定义异常
        }

        return null; // 返回null表示读取失败

    }




    private List<EsDocInsertVo> tansFromData2(MallProductInfo mallProductInfo, List<MallProductSkuInfo> mallProductSkuInfos) {
        //构建返回结果集
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
        esDocInsertVo.setId(String.valueOf(mallProductInfo.getId()));
        esDocInsertVo.setIndexName(INDEX_NAME);
        esDocInsertVo.setTypeName("_doc");
        mallProductInfo.setmallProductSkuInfoList(mallProductSkuInfos);
        // TODO spu和sku信息
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(mallProductInfo), Map.class);
        if (mallProductInfo.getType() != null){
            map.put("type",mallProductInfo.getType());
            map.put("typeName",productTypeInfoService.selectMallProductTypeInfoById(Long.valueOf(mallProductInfo.getType())).getName());
            map.put("imgs",mallProductInfo.getImg()+mallProductInfo.getCarouselImages());
        }
        // data赋值
        esDocInsertVo.setData(map);
        esDocInsertVos.add(esDocInsertVo);
        return esDocInsertVos;
    }

    private List<EsDocInsertVo> builderProductInfoToEs(List<MallProductInfo> mallProductInfos) {
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        mallProductInfos.stream().forEach(mallProductInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(String.valueOf(mallProductInfo.getId()));
            esDocInsertVo.setIndexName("mall_product");
            //对象转为Map
            Map<String, Object> data = JSON.parseObject(JSON.toJSONString(mallProductInfo), Map.class);
            esDocInsertVo.setData(data);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }


    @Override
    public void loadingProductInfoToEs() {
        //查询所有商品信息
        List<MallProductInfo> mallProductInfos = mallProductInfoMapper.selectMallProductInfoList(new MallProductInfo());
        if (mallProductInfos == null || mallProductInfos.size() == 0) {
            log.info("暂无需要同步的商品");
        }
        //调用ES查询索引是否存在
        R<Boolean> indexExit = remoteEsIndexService.indexExit("mall_product");
        if (!indexExit.getData()) {
            log.info("mall_product索引不存在,调用ES服务创建索引");
            //创建索引
//            R<Boolean> indexCreate = remoteEsIndexService.indexCreate("mall_product");
//            if (!indexCreate.getData()) {
//                log.info("创建mall_product索引失败");
//            }
            //批量同步商品信息到ES
            //构建参数
            List<EsDocInsertVo> esDocInsertVo = builderProductInfoToEs(mallProductInfos);
            //调用ES服务批量插入文档
            R<Boolean> batchInsert = remoteEsDocService.batchInsertDocs(esDocInsertVo);
            if (batchInsert.getData()) {
                log.info("批量同步商品信息到ES成功");
            }
        }

    }


    private List<EsDocInsertVo> builderProductInfoToEs2(MallProductInfo mallProductInfoo, List<MallProductSkuInfo> mallProductInfos) {
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
        esDocInsertVo.setIndexName("log_info");
        Map<String,Object> logInfo = new HashMap<>();
        logInfo.put("ip","127.0.0.1");
        logInfo.put("user","admin");
        logInfo.put("url","http://localhost:8080/bawei/mall/product/info/1");
        logInfo.put("method","GET");

        esDocInsertVo.setData(logInfo);
        esDocInsertVos.add(esDocInsertVo);
        return esDocInsertVos;
    }


    @Override
    public void updStatus(MallProductInfo mallProductInfo) {
        int i = mallProductInfoMapper.updStatus(mallProductInfo);
        if (i == 0){
            throw new ServiceException("修改商品状态失败");
        }
    }

    /**
     * 猜你喜欢
     * @return
     */
    @Override
    public List<MallProductInfoNew> guessYouLike(Integer pageNum, Integer pageSize) {
        return mallProductInfoMapper.guessYouLike(pageNum,pageSize);
    }

    /**
     * 根据品牌ID查询商品
     */
    @Override
    public List<MallProductInfoNew> productInfoByBrandId(Integer brandId) {
        return mallProductInfoMapper.productInfoByBrandId(brandId);
    }



    /**
     * 商品详情界面
     * @param id
     * @return
     */
    @Override
    public ProductDetailsNewResponse detail(Long id) {
        ProductDetailsNewResponse productDetailsNewResponse = new ProductDetailsNewResponse();
        // TODO 商品基本信息
        MallProductInfoNew mallProductInfo = mallProductInfoMapper.selectMallProductInfoNewById(id);
        productDetailsNewResponse.setProduct(mallProductInfo);
        // TODO 商品品牌信息
        MallProductBrandInfoNew mallProductBrandInfoNew = productBrandInfoService.selectMallProductBrandInfoNewById(Long.valueOf(mallProductInfo.getBrand()));
        productDetailsNewResponse.setBrand(mallProductBrandInfoNew);
        // TODO 商品属性
        String productAttribute = "[\n" +
                "            {\n" +
                "                \"id\": 43,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"颜色\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 0,\n" +
                "                \"inputList\": \"\",\n" +
                "                \"sort\": 100,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 1,\n" +
                "                \"type\": 0\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 44,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"容量\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 1,\n" +
                "                \"inputList\": \"16G,32G,64G,128G,256G,512G\",\n" +
                "                \"sort\": 0,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 0,\n" +
                "                \"type\": 0\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 45,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"屏幕尺寸\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 0,\n" +
                "                \"inputList\": \"\",\n" +
                "                \"sort\": 0,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 0,\n" +
                "                \"type\": 1\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 46,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"网络\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 1,\n" +
                "                \"inputList\": \"3G,4G,5G,WLAN\",\n" +
                "                \"sort\": 0,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 0,\n" +
                "                \"type\": 1\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 47,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"系统\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 1,\n" +
                "                \"inputList\": \"Android,IOS\",\n" +
                "                \"sort\": 0,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 0,\n" +
                "                \"type\": 1\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 48,\n" +
                "                \"productAttributeCategoryId\": 3,\n" +
                "                \"name\": \"电池容量\",\n" +
                "                \"selectType\": 0,\n" +
                "                \"inputType\": 0,\n" +
                "                \"inputList\": \"\",\n" +
                "                \"sort\": 0,\n" +
                "                \"filterType\": 0,\n" +
                "                \"searchType\": 0,\n" +
                "                \"relatedStatus\": 0,\n" +
                "                \"handAddStatus\": 0,\n" +
                "                \"type\": 1\n" +
                "            }\n" +
                "        ]";
        List<ProductAttribute> productAttributeList = JSONArray.parseArray(productAttribute, ProductAttribute.class);
        productDetailsNewResponse.setProductAttributeList(productAttributeList);
        // TODO 商品属性值
        String productAttributeValue = "[\n" +
                "            {\n" +
                "                \"id\": 288,\n" +
                "                \"productId\": 27,\n" +
                "                \"productAttributeId\": 43,\n" +
                "                \"value\": \"黑色,蓝色\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 289,\n" +
                "                \"productId\": 27,\n" +
                "                \"productAttributeId\": 45,\n" +
                "                \"value\": \"5.8\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 290,\n" +
                "                \"productId\": 27,\n" +
                "                \"productAttributeId\": 46,\n" +
                "                \"value\": \"4G\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 291,\n" +
                "                \"productId\": 27,\n" +
                "                \"productAttributeId\": 47,\n" +
                "                \"value\": \"Android\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 292,\n" +
                "                \"productId\": 27,\n" +
                "                \"productAttributeId\": 48,\n" +
                "                \"value\": \"3000ml\"\n" +
                "            }\n" +
                "        ]";
        List<ProductAttributeValue> productAttributeValueList = JSONArray.parseArray(productAttributeValue, ProductAttributeValue.class);
        for (ProductAttributeValue attributeValue : productAttributeValueList) {
            attributeValue.setProductId(Math.toIntExact(mallProductInfo.getId()));
        }
        productDetailsNewResponse.setProductAttributeValueList(productAttributeValueList);
        // TODO sku
        List<SkuStock> skuStockList = getSkuStockList();
        for (SkuStock skuStock : skuStockList) {
            skuStock.setProductId(Math.toIntExact(mallProductInfo.getId()));
        }
        productDetailsNewResponse.setSkuStockList(skuStockList);

        return productDetailsNewResponse;
    }

    public List<SkuStock> getSkuStockList() {
        String productSku = "[\n" +
                "            {\n" +
                "                \"id\": 98,\n" +
                "                \"productId\": 27,\n" +
                "                \"skuCode\": \"201808270027001\",\n" +
                "                \"price\": 2699.00,\n" +
                "                \"stock\": 86,\n" +
                "                \"lockStock\": -24,\n" +
                "                \"spData\": \"[{\\\"key\\\":\\\"颜色\\\",\\\"value\\\":\\\"黑色\\\"},{\\\"key\\\":\\\"容量\\\",\\\"value\\\":\\\"32G\\\"}]\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 99,\n" +
                "                \"productId\": 27,\n" +
                "                \"skuCode\": \"201808270027002\",\n" +
                "                \"price\": 2999.00,\n" +
                "                \"stock\": 100,\n" +
                "                \"lockStock\": 0,\n" +
                "                \"spData\": \"[{\\\"key\\\":\\\"颜色\\\",\\\"value\\\":\\\"黑色\\\"},{\\\"key\\\":\\\"容量\\\",\\\"value\\\":\\\"64G\\\"}]\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 100,\n" +
                "                \"productId\": 27,\n" +
                "                \"skuCode\": \"201808270027003\",\n" +
                "                \"price\": 2699.00,\n" +
                "                \"stock\": 100,\n" +
                "                \"lockStock\": 0,\n" +
                "                \"spData\": \"[{\\\"key\\\":\\\"颜色\\\",\\\"value\\\":\\\"蓝色\\\"},{\\\"key\\\":\\\"容量\\\",\\\"value\\\":\\\"32G\\\"}]\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 101,\n" +
                "                \"productId\": 27,\n" +
                "                \"skuCode\": \"201808270027004\",\n" +
                "                \"price\": 2999.00,\n" +
                "                \"stock\": 100,\n" +
                "                \"lockStock\": 0,\n" +
                "                \"spData\": \"[{\\\"key\\\":\\\"颜色\\\",\\\"value\\\":\\\"蓝色\\\"},{\\\"key\\\":\\\"容量\\\",\\\"value\\\":\\\"64G\\\"}]\"\n" +
                "            }\n" +
                "        ]";
        List<SkuStock> skuStockList = JSONArray.parseArray(productSku, SkuStock.class);
        return skuStockList;
    }

//    @Override
//    public HashMap<String, Object> detail(Long id) {
//        HashMap<String, Object> map = new HashMap<>();
//        MallProductInfoNew mallProductInfo = mallProductInfoMapper.selectMallProductInfoNewById(id);
//        map.put("product",mallProductInfo);
//        MallProductBrandInfoNew mallProductBrandInfoNew = productBrandInfoService.selectMallProductBrandInfoNewById(Long.valueOf(mallProductInfo.getBrand()));
//        map.put("brand",mallProductBrandInfoNew);
//        ProductInfoResponse productInfoResponse = selectMallProductInfoById(id);
//        map.put("skuStockList",productInfoResponse.getSkuInfoList());
//        return map;
//    }



    /**
     * 查询用户有没有关注这个品牌
     * @param brandId
     * @return
     */
    @Override
    public MallProductUserInfo selectMallProductUserInfo(Integer brandId) {
        User user = getInfo();
        return mallProductInfoMapper.selectMallProductUserInfo(brandId,user.getId());
    }

    /**
     * 添加关注
     * @param mallProductUserInfo
     */
    @Override
    public void addCollection(MallProductUserInfo mallProductUserInfo) {
        User user = getInfo();
        mallProductUserInfo.setMemberId(user.getId());
        mallProductUserInfo.setMemberNickname(user.getNickname());
        mallProductInfoMapper.addCollection(mallProductUserInfo);
    }

    /**
     * 取消关注
     * @param brandId
     */
    @Override
    public void deleteCollection(Integer brandId) {
        User user = getInfo();
        mallProductInfoMapper.deleteCollection(brandId,user.getId());
    }

    /**
     * 查询地址列表
     * @return
     */
    @Override
    public List<MallProductAddrInfo> fetchAddressList() {
        User user = getInfo();
        return mallProductInfoMapper.fetchAddressList(user.getId());
    }

    /**
     * 地址解析
     * @param address
     * @return
     */
    @Override
    public MallProductAddrInfo analyzeAddress(String address) {
        String addressStr = analyzeAddress.analyzeAddres(address);
        MallProductAddressResult addressInfo = JSON.parseObject(addressStr, MallProductAddressResult.class);
        Object data =  addressInfo.getData();
        MallProductAddressInfo addressInfo1 = JSON.parseObject(JSON.toJSONString(data), MallProductAddressInfo.class);
        MallProductAddrInfo memberAddressInfo = new MallProductAddrInfo();
        memberAddressInfo.setName(addressInfo1.getPerson());
        memberAddressInfo.setPhoneNumber(addressInfo1.getPhoneNum());
        memberAddressInfo.setDefaultStatus(0);
        memberAddressInfo.setProvince(addressInfo1.getProvince());
        memberAddressInfo.setCity(addressInfo1.getCity());
        memberAddressInfo.setRegion(addressInfo1.getCounty());
        memberAddressInfo.setTown(addressInfo1.getTown());
        memberAddressInfo.setDetailAddress(addressInfo1.getDetail());

        return  memberAddressInfo;
    }

    /**
     * 添加地址
     * @param mallProductAddrInfo
     */
    @Override
    public void addAddress(MallProductAddrInfo mallProductAddrInfo) {
        User user = getInfo();
        mallProductAddrInfo.setMemberId(Long.valueOf(user.getId()));
        mallProductInfoMapper.addAddress(mallProductAddrInfo);
    }

    /**
     * 查询关注列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MallProductUserInfo> selectMallProductUserInfoList(Integer pageNum, Integer pageSize) {
        User user = getInfo();
        return mallProductInfoMapper.selectMallProductUserInfoList(pageNum,pageSize,user.getId());
    }

    /**
     * 根据关键字查询商品
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MallProductInfoNew> search(String keyword, Integer pageNum, Integer pageSize) {
        return mallProductInfoMapper.search(keyword,pageNum,pageSize);
    }

    /**
     * 清空关注列表
     */
    @Override
    public void clear() {
        User user = getInfo();
        mallProductInfoMapper.clear(user.getId());
    }

    @Override
    public List<MallProductInfoNew> hotProductList(Integer pageNum, Integer pageSize) {
        PageInfo<MallProductInfoNew> mallProductInfoNewPageInfo = productBrandInfoServiceImpl.newProductList(pageNum, pageSize);
        return mallProductInfoNewPageInfo.getList();
    }


    /**
     * 获取用户信息
     */
    public User getInfo() {
        String token = redisTemplate.opsForValue().get("token");
        String cusUserJSONString = redisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(cusUserJSONString, User.class);
        return user;
    }


}
